package com.cn.bulu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.cn.bulu.constant.PayMethod;
import com.cn.bulu.constant.WorkerType;
import com.cn.bulu.dao.*;
import com.cn.bulu.pojo.*;
import com.cn.bulu.service.CustomerService;
import com.cn.bulu.service.IndentService;
import com.cn.bulu.service.PayService;
import com.cn.bulu.service.WorkerWalletRecordService;
import com.cn.bulu.utils.ClothCurtain.Arith;
import com.cn.bulu.utils.DateUtils;
import com.cn.bulu.utils.MapToStringUtil;
import com.cn.bulu.utils.alipay.config.AlipayConfig;
import com.cn.bulu.utils.alipay.util.AlipayCore;
import com.cn.bulu.utils.jiguang.Jiguang;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("payService")
public class PayServiceImpl implements PayService {
	
	private Logger logger = Logger.getLogger(PayServiceImpl.class);
	@Resource
	private IndentDao indentDao;
	@Resource
	private MerchantsWalletRecordDao merchantsWalletRecordDao;
	@Resource
	private WorkerWalletRecordDao workerWalletRecordDao;
	@Resource
	private CustomerWalletRecordDao  customerWalletRecordDao;
	@Resource
	private MerchantsDao merchantsDao;
	@Resource
	private WorkerDao workerDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private CustomerDao customerDao;
	@Resource
	private WorkerWalletRecordService workerWalletRecordService;
	@Resource
	private IndentService indentService;
	@Resource
	private CustomerService customerService;
	
	
	
	//阿里支付宝回调函数处理业务
	public int alipayNotifyProcessService(HttpServletRequest request) {
		//标记回调开始
		logger.error("============================回调进入业务处理层=====================================");
		
		Map<String, String> params = new HashMap<String, String>();
		//获取支付宝回调参数名
		Enumeration<?> pNames = request.getParameterNames();
		//遍历参数然后将其键值对存放在params集合中
		while (pNames.hasMoreElements()) {
			String pName = (String) pNames.nextElement();
			params.put(pName, request.getParameter(pName));
		}
		logger.error("参数内容======:" + MapToStringUtil.transMapToString(params)+"==================");
		
		return alipayNotifySuccess(request,params);
	}

	/**
	 * 判断支付宝是否认定买家付款成功,如果成功继续业务处理,否则返回失败状态400
	 * @param request
	 * 		 httpRequest
	 * @param params
	 * 		 获取的支付宝回调参数集合AlipayCore.logResult(out_trade_no + " recharge is failure", "failure");
	 * @return
	 */
	private int alipayNotifySuccess(HttpServletRequest request, Map<String, String> params) {
		try {
			// 交易状态 只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，支付宝才会认定为买家付款成功。
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
			logger.error("==========================返回的trade_status=" + trade_status+"====================");
			//判断支付宝是否认定买家付款成功
			boolean tradeStatusFlag = "TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status);
			//返回结果
			return tradeStatusFlag==true?alipayNotifyRSA(request, params):400;
			
		} catch (UnsupportedEncodingException e) {
			logger.error("====================="+"判断支付宝是否认定买家付款成功时出错"+"======================");
			e.printStackTrace();
		}
		return 400;
	}

	/**
	 * 支付宝认定买家付款成功需要进行验签,如果验签失败返回失败标志400,否则继续业务逻辑
	 * @param request
	 * @param params
	 * @return
	 */
	private int alipayNotifyRSA(HttpServletRequest request, Map<String, String> params) {
		
		// sign代表签名
		String sign = request.getParameter("sign");
		logger.error("====签名sign的值===:"+sign+"=========================");
		boolean flag;
		try {
			
			// 使用RSA的验签方法，通过签名字符串、签名参数（经过base64解码）及支付宝公钥验证签名。
			flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key,
					AlipayConfig.input_charset, AlipayConfig.sign_type);
			logger.error("======================验签结果=" + flag+"=============================");
			
			return flag==true?alipayNotifyAppId(request,params):400;
		} catch (AlipayApiException e) {
			logger.error("====================="+"判断支付宝进行验签的时候出错"+"======================");
			e.printStackTrace();
		}
		return 400;
	}
	
	/**
	 * 验证app_id是否为该商户本身,如果不是商户本身返回失败状态400,否则继续业务逻辑
	 * @param request
	 * @param params
	 * @return
	 */
	private int alipayNotifyAppId(HttpServletRequest request, Map<String, String> params) {
		try {
			// 验证app_id是否为该商户本身
			String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"), "UTF-8");
			logger.error("==========================返回的app_id=" + app_id+"====================");
			//获取检验结果
			boolean flag = AlipayConfig.app_id.equals(app_id);
			logger.error("=================验证app_id是否为该商户本身结果=" + flag+"====================");
			
			return flag==true?alipayNotifyseller(request,params):400;
			
		} catch (UnsupportedEncodingException e) {
			logger.error("====================="+"验证app_id是否为该商户本身出错"+"======================");
			e.printStackTrace();
		}
		return 400;
	}
	
	/**
	 * 校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	 * 如果校验失败返回失败状态400,否则继续业务处理
	 * @param request
	 * @param params
	 * @return
	 */
	private int alipayNotifyseller(HttpServletRequest request, Map<String, String> params) {
		
		try {
			//获取需要验证的参数
			String seller_id = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"), "UTF-8");
			String seller_email = new String(request.getParameter("seller_email").getBytes("ISO-8859-1"), "UTF-8");
			//获取校验结果
			boolean flag = AlipayConfig.seller.equals(seller_id)|| AlipayConfig.seller.equals(seller_email);
			logger.error("====================="+"验证seller_id（或者seller_email)的结果="+flag+"======================");
			logger.error("=====================seller_id="+seller_id +",============seller_email="+seller_email);
			return flag==true?alipayNotifyAllParams(request,params):400;
		} catch (UnsupportedEncodingException e) {
			logger.error("====================="+"验证seller_id（或者seller_email)出错"+"======================");
			e.printStackTrace();
		}
		return 400;
	}
	
	/**
	 * 准备业务处理需要的参数,并根据业务类型进行业务分发
	 * @param request
	 * @param params
	 * @return
	 */
	private int alipayNotifyAllParams(HttpServletRequest request, Map<String, String> params) {
		//参数准备
		int result = 400;
		logger.error("===========================进入业务分发层===request=="+request.toString()+"==params=="+params.toString()+"========================");
		try {
			// 商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
			logger.error("===========================商户订单号===out_trade_no=="+out_trade_no+"========================");
			// 交易金额
			String total_amount = request.getParameter("total_amount");
			logger.error("===========================交易金额===total_amount=="+total_amount+"========================");
			// 支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
			logger.error("===========================支付宝交易号===trade_no=="+trade_no+"========================");
			// 交易金额
			//获取回传参数并解析为JSONObject对象
			String passback_paramsStr = request.getParameter("passback_params");
			logger.error("===========================获取回传参数并解析为JSONObject对象===passback_paramsStr=="+passback_paramsStr+"========================");
			
		
			
			JSONObject passback_params=null;
			if(passback_paramsStr !=null && !("".trim().equals(passback_paramsStr))){
				passback_params= JSONObject.parseObject(passback_paramsStr);
				Integer indentId=passback_params.getInteger("indentId");
				
				if( indentId !=null && indentId != 0){ //订单非空，并且不为充值业务
					Map<String,Object>userCustomerMap=customerService.isCustomerOrdered(indentId);
					if(userCustomerMap !=null && !userCustomerMap.isEmpty()){
						Map<String,Object> map=new HashMap<>();
						map.put("status", 1);
						map.put("phone", userCustomerMap.get("phone"));
						userDao.updateUserCustomer(map);
					}
					  //分配利润
					indentService.updateProfitOfAgentors(indentId);
				}
				
	            // 打印相关结果
				if(passback_params.get("payer") == null){//商家支付
					// businessType,该次交易的具体操作内容 0测量,1安装,2维修,3加价悬赏,5充值
					int businessType =(Integer)passback_params.get("type");
					if(businessType == 0 || businessType == 1 || businessType == 2){
						result = payMoneyAfter(request, out_trade_no, total_amount,trade_no,passback_params);
					}else if(businessType == 3){
						result = addPriceAfter(request, out_trade_no, total_amount, trade_no,passback_params);
					}else if(businessType == 5){
						result = rechageAfter(request, out_trade_no, total_amount, trade_no,passback_params);
					}else if(businessType == 4){
						result = payDifference(request,out_trade_no,total_amount,trade_no,passback_params);
					}else{
						logger.error("====================付款操作不明确 0测量,1安装,2维修,3加价悬赏,4补差价,5充值,选择不在这里面===========");
						AlipayCore.logResult("付款操作不明确", "0测量,1安装,2维修,3加价悬赏,4补差价,5充值,选择不在这里面");
					}
					logger.debug("===alipayNotifyAllParams==if=result===>"+result);
				}else {//顾客支付
					int businessType =Integer.parseInt((String) passback_params.get("type"));
					if(businessType==6){  //充值
						result=rechageAfter(request, out_trade_no, total_amount, trade_no, passback_params);
					}else{  //支付
						result=payResultFromCustomer(request,out_trade_no,total_amount,trade_no,passback_params);
					}
					logger.debug("===alipayNotifyAllParams==else=result===>"+result);
				}
			}
		} catch (Exception e) {
			logger.error("==========================="+"获取订单所有参数时报错"+"=================================");
			e.printStackTrace();
			return result;
		}
		return result;
	}
	

	/**
	 * HttpServletRequest request, String out_trade_no, String total_amount, String trade_no,
			JSONObject passback_params
	 * @param out_trade_no
	 * @return
	 */
	public int payResultFromCustomer(HttpServletRequest request, String out_trade_no,String total_amount,String trade_no,JSONObject passback_params){
		Integer customerWalletRecordId=(Integer)passback_params.get("customerRecordId");
		Map<String,Object> param = new HashMap<>();
		param.put("orderNo", out_trade_no);
		param.put("status", 0);
		param.put("customerWalletRecordId", customerWalletRecordId);
		logger.debug("===payResultFromCustomer=========param>"+param.toString());
		CustomerWalletRecord customerWalletRecord=customerWalletRecordDao.selectCustomerWalletRecordById(param);
		boolean flag = customerWalletRecord.getFinalLostMoney().compareTo(Double.valueOf(total_amount))==0;
		logger.debug("===payResultFromCustomer=========flag>"+flag);
		return flag==true?payResultUpdate(request,trade_no,passback_params,customerWalletRecord):400;
	}
	
	private int payResultUpdate(HttpServletRequest request, String trade_no, JSONObject passback_params,
			CustomerWalletRecord customerWalletRecord) {
		// TODO Auto-generated method stub
		logger.debug("===============开始更新订单状态=========================");
		try {
		//1:回调处理
		Indent indent=indentDao.selectIndentById(String.valueOf(customerWalletRecord.getIndentId()));
		if(indent !=null){
			Integer type=indent.getType();
			switch (type) {
				case 0://测量
					if(indent.getStatus()==4) {
						Map<String, Object> indentMap = customerDao.selectIndentMap(indent.getIndentId());
						if(indentMap!=null){
							//极光推送
							Jiguang.JpushIndent(indentMap);
							indent.setStatus(9);
						}	
					}else if(indent.getStatus()==2){
						indent.setStatus(3);
					}
					break;
				case 1:	//安装
					if(indent.getStatus()==4) {
						Map<String, Object> indentMap = customerDao.selectIndentMap(indent.getIndentId());
						if(indentMap!=null){
							//极光推送
							Jiguang.JpushIndent(indentMap);
							indent.setStatus(9);
						}
					}
					break;
				case 4://普通订单
					indent.setStatus(3);
				default:
					break;
			}
			
			customerDao.updateMeterIndent(indent);
			
			//更新记录
			Map<String, Object> customerWalletReocrdparams = new HashMap<>();
			customerWalletReocrdparams.put("status", 1);
			customerWalletReocrdparams.put("tradeNo", trade_no);
			customerWalletReocrdparams.put("recordEndTime", DateUtils.getDateTime());
			customerWalletReocrdparams.put("customerWalletRecordId", customerWalletRecord.getCustomerWalletRecordId());
			int records=customerWalletRecordDao.updateCustomerWalletReocrd(customerWalletReocrdparams);
			System.out.println("===============结束更新订单状态=========================");
			return records>0?200:400;
		}
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
	return 400;
	}

	/**
	 * 支付宝支付补差价的回调业务处理,先进行比对订单号的总价是否一样和订单号是不是我们自己的
	 * @param request
	 * @param out_trade_no
	 * @param total_amount
	 * @param trade_no
	 * @param passback_params
	 * @return
	 */
	private int payDifference(HttpServletRequest request, String out_trade_no, String total_amount, String trade_no,
			JSONObject passback_params) {
		logger.error("===============================补差价业务开始===================================");
		String differenceIds = String.valueOf(passback_params.get("differenceIds"));//差价的id数组
		Integer merchantsId = (Integer)passback_params.get("merchantsId");//商家或者个人id
		//将差价id解析为json数组
		JSONArray idArray = JSONObject.parseArray(differenceIds);
		//根据数组查找需要处理的补差价
		List<Map<String, Object>> differenceList = merchantsDao.selectDifferences(merchantsId, idArray);
		boolean totalFlag = getTotalMoneyIsFlag(differenceList, Double.valueOf(total_amount));
		String orderNo = String.valueOf(passback_params.get("orderNo"));
		boolean orderNoFlag = out_trade_no.equals(orderNo);
		logger.error("==============补差价进行的检验订单和="+totalFlag+orderNoFlag+"==========================================");
		return (totalFlag==true&&orderNoFlag==true)?payDifferenceUpdate(request,differenceList,Double.valueOf(total_amount),trade_no):400;
	}
	/**
	 * 补差价更新数据库
	 * @param request
	 * @param differenceList
	 * @param trade_no
	 * @return
	 */
	private int payDifferenceUpdate(HttpServletRequest request, List<Map<String, Object>> differenceList,
			Double total_amount, String trade_no) {
		Map<String,Object> param = new HashMap<>();
		param.put("tradeNo", trade_no);
		param.put("status", 1);
		param.put("method", PayMethod.ALIPAY.getMethod());
		param.put("recordEndTime", DateUtils.getDateTime());
		//余额支付差价
		for(int a = 0;a<differenceList.size();a++){
			param.put("merchantsWalletRecordId", (Integer)differenceList.get(a).get("differenceId"));
			Double toWorker = (Double)differenceList.get(a).get("differencePrice");
			Integer workerId = (Integer)differenceList.get(a).get("workerId");
			Integer differenceIndentId = (Integer)differenceList.get(a).get("indentId");
			int update = updateDifferenceToWorker(differenceIndentId,toWorker,workerId);
			// 把状态改为已支付
			if(update>0){
				// 把状态改为已支付
				merchantsWalletRecordDao.updateMerchantsWalletRecord(param);
			}
		}
		return 200;
	}
	/**
	 * 在补差价的时候补给订单对应的工人的差价钱
	 * @param indentId
	 * @param toWorker
	 * @param workerId
	 * @return
	 */
	private int updateDifferenceToWorker(Integer indentId, Double toWorker,Integer workerId) {
		Double workerWallet = workerDao.selectWallet(workerId);
		workerWallet = Arith.add(workerWallet, toWorker);
		//给工人钱包加上商家取消扣除的钱
		Map<String, Object> send = new HashMap<>();
		send.put("workerId", workerId);
		send.put("wallet", workerWallet);
		//更新工人钱包
		workerDao.updateWalletComple(send);
		int update = workerWalletRecordService.insertWorkerWalletRecord(workerId, indentId, 2,
				toWorker, null, null, toWorker, null, null,null, WorkerType.PRICE_DIFFERENCE.getIndex(), 1, "商家支付补差价", 0, "余额获取补差价");
		return update>0?update:0;
	}

	/**
	 * 计算补差价是否和数据库一样多的总价
	 * @param differenceList
	 * @param totalMoney
	 * @return
	 */
	private boolean getTotalMoneyIsFlag(List<Map<String, Object>> differenceList, Double totalMoney) {
		Double differenceTotalMoney = 0.00;
		for(int a = 0;a<differenceList.size();a++){
			Double differencePrice = (Double)differenceList.get(a).get("differencePrice");
			differenceTotalMoney = Arith.add(differenceTotalMoney, differencePrice);
		}
		return differenceTotalMoney.compareTo(totalMoney)==0;
	}

	/**
	 * 区分是工人充值还是商家或者个人充值
	 * @param request
	 * @param out_trade_no
	 * @param total_amount
	 * @param trade_no
	 * @param passback_params
	 * @return
	 */
	private int rechageAfter(HttpServletRequest request, String out_trade_no, String total_amount, String trade_no,
			JSONObject passback_params) {
		int result = 400;
		logger.error("==========================分发工人或者商家提现=====================");
		String recharge = String.valueOf(passback_params.get("recharge"));
		
		if(recharge.equals("merchantsRecharge")){//商家充值
			result = rechargeMerchants(request,out_trade_no,total_amount,trade_no,passback_params);
		}else if(recharge.equals("workerRecharge")){//工人充值
			result = rechargeWorker(request,out_trade_no,total_amount,trade_no,passback_params);
		}else if(recharge.equals("customerRecharge")){//顾客充值
			result=rechargeCustomer(request,out_trade_no,total_amount,trade_no,passback_params);
		}else{
			logger.error("==========================未知身份充值=====================");
			return result;
		}
		return result;
	}
	
	
	/**
	 * 
	 * @param request
	 * @param out_trade_no
	 * @param total_amount
	 * @param trade_no
	 * @param passback_params
	 * @return
	 */
	private int rechargeCustomer(HttpServletRequest request, String out_trade_no, String total_amount, String trade_no,
			JSONObject passback_params) {
		// TODO Auto-generated method stub
		logger.error("=================顾客充值查找单号=======================");
		Integer customerWalletRecordId=Integer.parseInt((String)passback_params.get("customerRecordId"));
		Map<String,Object> param = new HashMap<>();
		param.put("orderNo", out_trade_no);
		param.put("status", 0);
		param.put("customerWalletRecordId", customerWalletRecordId);
		CustomerWalletRecord customerWalletRecord=customerWalletRecordDao.selectCustomerWalletRecordById(param);
		boolean flag = customerWalletRecord.getFinalGetMoney().compareTo(Double.valueOf(total_amount))==0;
		return flag==true?rechargeCustomerUpdate(request,trade_no,passback_params,customerWalletRecord):400;
	}

	/**
	 * 
	 * @param request
	 * @param trade_no
	 * @param passback_params
	 * @param customerWalletRecord
	 * @return
	 */
	private int rechargeCustomerUpdate(HttpServletRequest request, String trade_no, JSONObject passback_params,
			CustomerWalletRecord customerWalletRecord) {
		// TODO Auto-generated method stub
		logger.error("=================顾客充值更新数据=======================");
		Map<String,Object> param = new HashMap<>();
		Customer customer=customerDao.getCustomerById(customerWalletRecord.getCustomerId());
		Double newWalet = Arith.add(customer.getWallet(), customerWalletRecord.getFinalGetMoney());
		param.put("wallet", newWalet);
		param.put("customerId", customerWalletRecord.getCustomerId());
		int n=customerDao.updateCustomerWallet(param);
		
		//修改交易记录
		if(n>0){
			Map<String, Object> customerWalletReocrdparams = new HashMap<>();
			customerWalletReocrdparams.put("status", 1);
			customerWalletReocrdparams.put("tradeNo", trade_no);
			customerWalletReocrdparams.put("recordEndTime", DateUtils.getDateTime());
			customerWalletReocrdparams.put("customerWalletRecordId", customerWalletRecord.getCustomerWalletRecordId());
			int records=customerWalletRecordDao.updateCustomerWalletReocrd(customerWalletReocrdparams);
			return records>0?200:400;
		}
		return 400;
	}

	/**
	 * 比较订单商号
	 * @param request
	 * @param out_trade_no
	 * @param total_amount
	 * @param trade_no
	 * @param passback_params
	 * @return
	 */
	private int rechargeWorker(HttpServletRequest request, String out_trade_no, String total_amount, String trade_no,
			JSONObject passback_params) {
		logger.error("=================工人充值查找单号=======================");
		//获取商家或者个人充值的时记录的id
		Integer workerWalletRecordId = (Integer)passback_params.get("walletRecordId");
		Map<String,Object> param = new HashMap<>();
		param.put("orderNo", out_trade_no);
		param.put("status", 0);
		param.put("workerWalletRecordId", workerWalletRecordId);
		WorkerWalletRecord workerWalletRecord = workerWalletRecordDao.selectWorkerWalletRecordById(param);
		boolean flag = workerWalletRecord.getFinalGetMoney().compareTo(Double.valueOf(total_amount))==0;
		return flag==true?rechargeWorkerUpdate(request,trade_no,passback_params,workerWalletRecord):400;
	}
	

	/**
	 * 工人充值业务跟新数据
	 * @param request
	 * @param trade_no
	 * @param passback_params
	 * @param workerWalletRecord
	 * @return
	 */
	private int rechargeWorkerUpdate(HttpServletRequest request, String trade_no, JSONObject passback_params,
			WorkerWalletRecord workerWalletRecord) {
		logger.error("=================工人充值更新数据=======================");
		Map<String,Object> param = new HashMap<>();
		// 找到用户原来的金额
		Worker worker = workerDao.selectWorker(workerWalletRecord.getWorkerId());
		// 原来的金额+本次充值的金额
		param.put("workerId", workerWalletRecord.getWorkerId());
		Double newWalet = Arith.add(worker.getWallet(), workerWalletRecord.getFinalGetMoney());
		param.put("wallet", newWalet);
		int updateWallet = workerDao.updateWalletComple(param);
		if(updateWallet>0){
			Map<String, Object> workerWalletReocrdparams = new HashMap<>();
			workerWalletReocrdparams.put("status", 1);
			workerWalletReocrdparams.put("tradeNo", trade_no);
			workerWalletReocrdparams.put("recordEndTime", DateUtils.getDateTime());
			workerWalletReocrdparams.put("workerWalletRecordId", workerWalletRecord.getWorkerWalletRecordId());
			int updateRecord = workerWalletRecordDao.updateWorkerWalletReocrd(workerWalletReocrdparams);
			return updateRecord>0?200:400;
		}
		
		return 400;
	}
	
	
	
	

	/**
	 * 商家或者个人充值
	 * @param request
	 * @param total_amount
	 * @param trade_no
	 * @param passback_params
	 * @return
	 */
	private int rechargeMerchants(HttpServletRequest request, String out_trade_no, String total_amount, String trade_no,
			JSONObject passback_params) {
		logger.error("=================商家或者个人充值查找单号=======================");
		//获取商家或者个人充值的时记录的id
		Integer merchantsWalletRecordId = (Integer)passback_params.get("walletRecordId");
		Map<String,Object> param = new HashMap<>();
		param.put("orderNo", out_trade_no);
		param.put("status", 0);
		param.put("merchantsWalletRecordId", merchantsWalletRecordId);
		//找到对应的记录
		MerchantsWalletRecord merchantsWalletRecord = merchantsWalletRecordDao.selectMerchantsWalletRecordById(param);
		
		return null!=merchantsWalletRecord?rechargeMerchantsTotalMoney(request,total_amount,trade_no,passback_params,merchantsWalletRecord):400;
		
	}
	/**
	 * 比较前后价钱是否对照
	 * @param request
	 * @param total_amount
	 * @param trade_no
	 * @param passback_params
	 * @param merchantsWalletRecord
	 * @return
	 */
	private int rechargeMerchantsTotalMoney(HttpServletRequest request,String total_amount, String trade_no, JSONObject passback_params,
			MerchantsWalletRecord merchantsWalletRecord) {
		boolean flag = merchantsWalletRecord.getFinalGetMoney().compareTo(Double.valueOf(total_amount))==0;
		logger.error("==========检验付钱的总金额======total_amount="+merchantsWalletRecord.getFinalGetMoney()+"===========");
		return flag==true?rechargeMerchantsUpdate(request,trade_no,passback_params,merchantsWalletRecord):400;
	}

	/**
	 * 商家充值提现更新数据库
	 * @param request
	 * @param trade_no
	 * @param passback_params
	 * @param merchantsWalletRecord
	 * @return
	 */
	private int rechargeMerchantsUpdate(HttpServletRequest request, String trade_no, JSONObject passback_params,
			MerchantsWalletRecord merchantsWalletRecord) {
		logger.error("=================商家或者工人充值更新数据库=======================");
		Map<String, Object> merchantsWalletReocrdparams = new HashMap<>();
		merchantsWalletReocrdparams.put("status", 1);
		merchantsWalletReocrdparams.put("tradeNo", trade_no);
		merchantsWalletReocrdparams.put("recordEndTime", DateUtils.getDateTime());
		merchantsWalletReocrdparams.put("merchantsWalletRecordId", merchantsWalletRecord.getMerchantsWalletRecordId());
		int update = merchantsWalletRecordDao.updateMerchantsWalletRecord(merchantsWalletReocrdparams);
		if(update > 0){
			Map<String, Object> merchantsMap = new HashMap<>();
			merchantsMap.put("merchantsId", merchantsWalletRecord.getMerchantsId());
			merchantsMap.put("wallet", merchantsWalletRecord.getWalletRecharge());
			int updatewallet = merchantsDao.updateWallet(merchantsMap);
			return updatewallet>0?200:400;
		}
		return 400;
	}

	/**
	 * 加价悬赏,需要将订单对应的加价悬赏加上对应的金额
	 * @param request
	 * @param out_trade_no
	 * @param total_amount
	 * @param trade_no
	 * @return
	 */
	private int addPriceAfter(HttpServletRequest request, String out_trade_no, String total_amount, String trade_no,
			JSONObject passback_params) {
		//寻找订单
		Integer merchantsWalletRecordId = (Integer)passback_params.get("walletRecordId");
		Map<String,Object> param = new HashMap<>();
		param.put("status", 0);
		param.put("merchantsWalletRecordId", merchantsWalletRecordId);
		MerchantsWalletRecord merchantsWalletRecord =merchantsWalletRecordDao.selectMerchantsWalletRecordById(param);
		
		return out_trade_no.equals(merchantsWalletRecord.getOrderNo())?adddPriceUpdate(request,total_amount,trade_no,passback_params,merchantsWalletRecord):400;
	}
	
	/**
	 * 加价数据更新
	 * @param request
	 * @param total_amount
	 * @param trade_no
	 * @param passback_params
	 * @return
	 */
	private int adddPriceUpdate(HttpServletRequest request, String total_amount, String trade_no,
			JSONObject passback_params,MerchantsWalletRecord merchantsWalletRecord) {
		//参数准备
		int result =400;
		//获取数据库的总金额
		Double totalMoneyFromDataBase = merchantsWalletRecord.getFinalLostMoney();
		//比对成功
		if(totalMoneyFromDataBase.compareTo(Double.valueOf(total_amount))==0){
			Map<String,Object> param = new HashMap<>();
			int relievedBao = (Integer)passback_params.get("relievedBao");
			Double relievePrice = (Double.valueOf(String.valueOf(passback_params.get("relievedPrice"))));
			Double addPrice = Double.valueOf(String.valueOf(passback_params.get("addPrice")));
			param.put("indentId", (Integer)passback_params.get("indentId"));
			Indent indent = indentDao.selectOneIndent(param);
			param.put("addPrice",Arith.add(addPrice,indent.getAddPrice()));
			param.put("relievedBao", relievedBao);
			if(merchantsWalletRecord.getMainMoney().compareTo(relievePrice)==0 && merchantsWalletRecord.getMainMoney().compareTo(0.00)>0){//说明之前没有选安心宝本次选择了
				param.put("merchantsPrice",Arith.add(indent.getMerchantsPrice(), relievedBao==0?0:relievePrice));
			}
			int update = indentDao.updateIndent(param);
			if(update>0){
				Map<String, Object> merchantsWalletReocrdparams = new HashMap<>();
				merchantsWalletReocrdparams.put("status", 1);
				merchantsWalletReocrdparams.put("tradeNo", trade_no);
				merchantsWalletReocrdparams.put("recordEndTime", DateUtils.getDateTime());
				merchantsWalletReocrdparams.put("merchantsWalletRecordId", (Integer)passback_params.get("walletRecordId"));
				merchantsWalletRecordDao.updateMerchantsWalletRecord(merchantsWalletReocrdparams);
				// 根据订单号查询订单信息
				Map<String, Object> indentMap = merchantsDao.selectIndent((Integer)passback_params.get("indentId"));
				Integer roomNumB = (Integer)indentMap.get("roomNumB");
				indentMap.put("roomNumB", roomNumB == null ? 0 : roomNumB);
				logger.error("========================================"+indentMap.toString());
				Jiguang.JpushIndent(indentMap);// 通过极光推送订单
				result = 200;
			}
		}
		return result;
	}
	
	

	/**
	 * 支付宝支付订单,支付成功需要更改数据库中indent表对应的订单的数据,并进行推送订单的
	 * @param request
	 * @param out_trade_no
	 * @param total_amount
	 * @param trade_no
	 * @return
	 */
	private int payMoneyAfter(HttpServletRequest request, String out_trade_no, String total_amount, String trade_no,
			JSONObject passback_params) {
		//获取钱包变动记录id
		Integer merchantsWalletRecordId = (Integer)passback_params.get("walletRecordId");
		//寻找记录订单
		Map<String,Object> param = new HashMap<>();
		param.put("orderNo", out_trade_no);
		param.put("merchantsWalletRecordId", merchantsWalletRecordId);
		MerchantsWalletRecord merchantsWalletRecord = merchantsWalletRecordDao.selectMerchantsWalletRecordById(param);
		boolean flag = merchantsWalletRecord.getOrderNo().equals(out_trade_no);
		logger.error("========是否从数据库查找出对应="+out_trade_no+"=订单="+merchantsWalletRecord.getOrderNo()+"=================");
		
		return true==flag?payMoneyAfterTotalMoney(request,merchantsWalletRecord,total_amount,trade_no,passback_params):400;
	}
	
	/**
	 * 比较支付时金额是否和回参数据中的总金额相等
	 * @param request
	 * 		httpRequest
	 * @param total_amount
	 * 		支付时的总金额
	 * @param trade_no
	 * 		支付宝产生的支付流水号
	 * @param passback_params
	 * 		回参集合
	 * @return
	 */
	private int payMoneyAfterTotalMoney(HttpServletRequest request,MerchantsWalletRecord merchantsWalletRecord, String total_amount, String trade_no,
			JSONObject passback_params) {
		//比较总价
		Double totalAmount = Double.valueOf(total_amount);
		Double totalPriceFromDateBase= merchantsWalletRecord.getFinalLostMoney();
		logger.error("totalAmount==="+totalAmount+"=====totalPriceFromDateBase==="+totalPriceFromDateBase);
		
		return totalAmount.compareTo(totalPriceFromDateBase)==0? payMoneyAfterUpdateIndent(request,trade_no,passback_params):400;
	}
	
	/**
	 * 修改数据库并推送消息,另外之前支付宝流水号存放在indent中，现在存放在merchantsWalletRecord
	 * @param request
	 * 		httpRequest
	 * @param trade_no
	 * 		支付宝流水号
	 * @param passback_params
	 * @return
	 */
	private int payMoneyAfterUpdateIndent(HttpServletRequest request, String trade_no, JSONObject passback_params) {
		//准备更新数据的参数
		Map<String, Object> params = new HashMap<>();
		params = getUpdateIndentData(passback_params);
		int update = indentDao.updateIndent(params);
		if(update>0){
			Map<String, Object> merchantsWalletReocrdparams = new HashMap<>();
			merchantsWalletReocrdparams.put("status", 1);
			merchantsWalletReocrdparams.put("recordEndTime", DateUtils.getDateTime());
			merchantsWalletReocrdparams.put("tradeNo", trade_no);
			merchantsWalletReocrdparams.put("merchantsWalletRecordId", (Integer)passback_params.get("walletRecordId"));
			merchantsWalletRecordDao.updateMerchantsWalletRecord(merchantsWalletReocrdparams);
			// 根据订单号查询订单信息
			Map<String, Object> indentMap = merchantsDao.selectIndent((Integer)params.get("indentId"));
			Integer roomNumB = (Integer)indentMap.get("roomNumB");
			indentMap.put("roomNumB", roomNumB == null ? 0 : roomNumB);
			logger.error("========================================"+indentMap.toString());
			Jiguang.JpushIndent(indentMap);// 通过极光推送订单
			return 200;
		}
		return 400;
	}

	/**
	 * 准备更新indent的数据
	 * @param passback_params
	 * 			回参集合
	 * @return
	 */
	private Map<String, Object> getUpdateIndentData(JSONObject passback_params) {
		Map<String, Object> params = new HashMap<>();
		params.put("indentId", (Integer)passback_params.get("indentId"));
		int relievedBao = (Integer)passback_params.get("relievedBao");
		Double merchantsPrice=(Double.valueOf(String.valueOf(passback_params.get("merchantsPrice"))));
		if(relievedBao==1){
			merchantsPrice = Arith.add(merchantsPrice, (Double.valueOf(String.valueOf(passback_params.get("relievedPrice")))));
		}
		params.put("merchantsPrice",merchantsPrice);
		params.put("workerRealPrice",(Double.valueOf(String.valueOf(passback_params.get("workerRealPrice")))));
		params.put("merchantsRealPrice",(Double.valueOf(String.valueOf(passback_params.get("merchantsRealPrice")))));
		params.put("indentPrice",(Double.valueOf(String.valueOf(passback_params.get("indentPrice")))));
		params.put("addPrice",(Double.valueOf(String.valueOf(passback_params.get("addPrice")))));
		params.put("relievedBao",relievedBao);
		params.put("motorNum", (Integer)passback_params.get("motorNum")==null?0:(Integer)passback_params.get("motorNum"));
		params.put("bigouNum", (Integer)passback_params.get("bigouNum")==null?0:(Integer)passback_params.get("bigouNum"));
		params.put("sizhuagouNum", (Integer)passback_params.get("sizhuagouNum")==null?0:(Integer)passback_params.get("sizhuagouNum"));
		params.put("status", 0);
		return params;
	}

	/**
	 * 计算总价
	 * @param passback_params
	 * 		回参集合
	 * @return
	 */
	@SuppressWarnings("unused")
	private Double getTotalMoney(JSONObject passback_params) {
		Double money = 0.00;
		Double merchantsPrice = Double.valueOf(String.valueOf(passback_params.get("merchantsPrice")));
		Double addPrice = Double.valueOf(String.valueOf(passback_params.get("addPrice")));
		int relievedBao = (Integer)passback_params.get("relievedBao");
		Double relievedPrice = Double.valueOf(String.valueOf(passback_params.get("relievedPrice")));
		money = Arith.add(merchantsPrice,  (Double)Arith.add(addPrice,relievedBao==0?0.00:relievedPrice));
		return money;
	}

	

}
